﻿using CPlatePrintSys.Win.ViewModels;
using Microsoft.Web.WebView2.Core;
using System;
using System.Configuration;
using System.Windows;
using System.Windows.Controls;

namespace CPlatePrintSys.Win.Views
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindowView : UserControl
    {
        private LoginWindowViewModel _viewModel;
        public LoginWindowView()
        {
            InitializeComponent();
            this.Loaded += LoginWindowView_Loaded;
            var url = ConfigurationManager.AppSettings["CPlateHost"];
            if (url != null && !url.EndsWith("/"))
            {
                url += "/";
            }
            url += "login";
            loginWebView.CoreWebView2InitializationCompleted += LoginWebView_CoreWebView2InitializationCompleted;
            loginWebView.Source = new Uri(url);
        }

        private void LoginWindowView_Loaded(object sender, RoutedEventArgs e)
        {
            _viewModel = this.DataContext as LoginWindowViewModel;
            if (_viewModel == null)
            {
                System.Diagnostics.Debug.WriteLine("警告: DataContext 在 Loaded 事件中仍然为 null。ViewModelLocator 可能已失败。");
            }
        }

        private void LoginWebView_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
        {
            if (e.IsSuccess)
            {
                // 订阅 WebMessageReceived 事件
                loginWebView.CoreWebView2.WebMessageReceived += LoginWebView_WebMessageReceived;
            }
        }

        private void LoginWebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            var message = e.WebMessageAsJson;
            _viewModel.HandleLogin(message);
        }
    }
}
